//
//  SleepVc.m
//  CareRing
//
//  Created  on 2024/12/17.
//
    

#import "SleepVc.h"
#import <QMUIKit/QMUIKit.h>
#import <Masonry/Masonry.h>
#import "ConfigModel.h"
#import "DynamicTextView.h"
#import "CADeviceInfo+description.h"
#import "UIButton+demoStyle.h"
#import "FunctionButton.h"
#import "Colors.h"
#import "ConfigModel.h"
#import "CARingSDK.h"
#import "CABLeService.h"
#import "CAHistoryDataSR03.h"
#import "CAActivityObjsCategoHead.h"
#import "SleepStagingV2.h"
#import "SleepSourceData.h"
#import <DateTools/DateTools.h>

@interface SleepVc ()<CABleDataProtocal, CABleScanProtocal>
@property(strong, nonatomic)DynamicTextView *textView;
@property(strong, nonatomic)FunctionButton * syncAndCalcBTn;

@property(strong, nonatomic)FunctionButton * cleanTxtBtn;

@property(strong, nonatomic)NSMutableArray<CAHistoryDataSR03 *> *hisCacheArray;

@property(assign, nonatomic)NSInteger countIdx, allCount;

@end

@implementation SleepVc

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    CARingSDK.instance.blescanDelegate = self;
    CARingSDK.instance.bleDataDelegate = self;

}

-(void)initUI
{
    WEAK_SELF
    [self customNavStyleNormal:@"Sleep" BackBlk:^{
        STRONG_SELF
        [strongSelf.navigationController popViewControllerAnimated:YES];
    }];
    [self.view addSubview:self.textView];
    [self.view addSubview:self.syncAndCalcBTn];
    [self.view addSubview:self.cleanTxtBtn];
    [self.textView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        make.leading.equalTo(self.view).offset(10);
        make.trailing.equalTo(self.view).inset(10);
        make.height.equalTo(self.view.mas_height).multipliedBy(2/5.0f);
    }];
    
    [self.cleanTxtBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.textView.mas_bottom).offset(10);
        make.leading.equalTo(self.textView);
        make.width.equalTo(self.textView.mas_width).multipliedBy(0.5);
        make.height.equalTo(@40);
    }];
    
    [self.syncAndCalcBTn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.cleanTxtBtn.mas_bottom).offset(40);
        make.leading.trailing.equalTo(self.textView);
        make.height.equalTo(@40);
    }];
}

/// calculate sleep after sync data
-(void)calcSleep
{
    // 去除 非佩戴和充电数据
    NSMutableArray <CAHistoryDataSR03 *> *usefulArray = [NSMutableArray new];
    for (CAHistoryDataSR03 *data in self.hisCacheArray) {
        if (!data.isWear.boolValue) {
            continue;
        }
        if (data.isCharging) {
            continue;
        }
        [usefulArray addObject:data];
    }
    
    // 准备计算
    SleepStagingV2 *calcObj = [[SleepStagingV2 alloc]init];
    NSMutableArray<SleepSourceData *> *sourceDatas = [NSMutableArray new];
    [usefulArray enumerateObjectsUsingBlock:^(CAHistoryDataSR03 * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        SleepSourceData *sd = [[SleepSourceData alloc]init];
        sd.time = obj.timeStamp;    //时间戳
        sd.soprtTimes = obj.soprtTimes;// 运动计数
        sd.deviceModifyHeartRate  = obj.deviceModifyHeartRate ; // 心率
        sd.hrv = obj.hrv;    // hrv
        sd.steps  = obj.steps; // 计步
        [sourceDatas addObject:sd];
    }];
    
    SleepStagingResultV2 *sleepResult = [calcObj findSleepDataByLib:sourceDatas];
    if (!sleepResult.stagingDataList.count) {
        [self.textView addNewText:@"Sleep calculation completed. No sleep."];
        
        return;
    }
    

    [sleepResult.stagingDataList enumerateObjectsUsingBlock:^(StagingDataV2 * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        DebugNSLog(@"sleep 计算 idx=%lu 睡眠开始 %@ 睡眠结束 %@", (unsigned long)idx,
                   [calcObj TestformatTimeStamp:obj.startTime],
                   [calcObj TestformatTimeStamp:obj.endTime]);
        NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:obj.startTime];
        NSDate *endDate = [NSDate dateWithTimeIntervalSince1970:obj.endTime];
        [self.textView addNewText:[NSString stringWithFormat:@"Sleep %lu:%@ - %@", idx,
                                   [startDate formattedDateWithFormat:_L2(L_DATE_FMT)],
                                   [endDate formattedDateWithFormat:_L2(L_DATE_FMT)]]];
        
        for (int i = 0; i < obj.ousideStagingList.count; i++) {
            
            NSDate *stgStartDate = [NSDate dateWithTimeIntervalSince1970:obj.ousideStagingList[i].list.firstObject.time.doubleValue];
            NSDate *stgEndDate = [NSDate dateWithTimeIntervalSince1970:obj.ousideStagingList[i].list.lastObject.time.doubleValue];

            [NSString stringWithFormat:@"  Stage %d:%@-%@", i, [stgStartDate formattedDateWithFormat:_L2(L_DATE_FMT)], [stgEndDate formattedDateWithFormat:_L2(L_DATE_FMT)]];
        }

    }];
    
}

-(DynamicTextView *)textView
{
    if (!_textView) {
        _textView = [[DynamicTextView alloc]initWithFrame:CGRectZero];
        _textView.layer.borderWidth = 1.0f;
        _textView.layer.borderColor = MAIN_BLUE.CGColor;
        [_textView setFont:[UIFont systemFontOfSize:15]];
    }
    return _textView;
}

-(FunctionButton *)syncAndCalcBTn
{
    if (!_syncAndCalcBTn) {
        _syncAndCalcBTn = [FunctionButton functionButton:_L2(L_SYNC_AND_CALC_SLEEP)];
        WEAK_SELF
        [_syncAndCalcBTn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            if (CARingSDK.instance.currentDevice.isConnected) {
                
                strongSelf.hisCacheArray = [NSMutableArray new];
                
                [CARingSDK.instance functionGetHistoryData];
            } else {
                [LTPHud.Instance showText:_L2(L_TIP_BLE_NOT_CONNECT) Lasting:2];
            }

        }];
    }
    return _syncAndCalcBTn;
}

-(FunctionButton *)cleanTxtBtn
{
    if (!_cleanTxtBtn) {
        _cleanTxtBtn = [FunctionButton functionButton:@"Clean text"];
        WEAK_SELF
        [_cleanTxtBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            [strongSelf.textView clearAllText];
        }];
    }
    return _cleanTxtBtn;
}

- (void)caBleCmdExcute:(EXCUTED_CMD)cmd Succ:(BOOL)isSucc Reason:(CA_CMD_EXECTE_ERROR_REASON)reason Data:(nonnull NSData *)originData { 
    
    if (cmd == EXCUTED_CMD_HIS_DATA && !isSucc ) {
//        self.historyCacheCount = 0;
//        self.fakeHisIncrease = 0;
        [self.hisCacheArray removeAllObjects];
        [CARingSDK.instance functionRsetTranslatingHistoryState];
        
        // 提示原因
        NSString *msg1 = [NSString stringWithFormat:_L2(L_CMD_EXCUTE_FMT_REASON), [CADeviceInfo descryOfErrorReason:reason], reason ];
        
        // 正在测量- 重试
        NSString *msg2 = @"";
        if (CA_REASON_1 == reason) {
            msg2 = _L2(L_TRY_AGAIN);
        }
        // 锻炼中- 先关闭锻炼
        if (CA_REASON_2 == reason) {
            msg2 = _L2(L_END_WK_FIRST);
        }
        [self showAlertWarningWithTitle:@"Error" Msg:[msg1 stringByAppendingString:msg2] btnCancel:_L2(L_OK) Compelete:nil];
    }
    
}

- (void)caBleDeviceBatteryLevel:(NSInteger)batteryLevel IsCharging:(BOOL)isCharging { 
    
}

- (void)caBleDeviceDidReadyForReadAndWrite:(nonnull CABLeService *)service { 
    
}

- (void)caBleDeviceInfo:(nonnull CADeviceInfo *)devInfo { 
    
}


- (void)caBleDeviceRealtimeTemperature:(nonnull NSNumber *)temperature { 
    
}

- (void)caBleDidConnectPeripheral:(nonnull CABLeService *)service { 
    
}

- (void)caBleDidDisconnectPeripheral:(nonnull CABLeService *)service {
    
    [LTPHud.Instance showText:_L2(L_TIP_BLE_NOT_CONNECT) Lasting:2];

}

- (void)caBleFailConnectPeripheral:(nonnull CBPeripheral *)peripheral Error:(nonnull NSError *)error { 
    
}


- (void)caBleHistorySr03Data:(CAHistoryDataSR03 *)hisData IsComplete:(BOOL)isComplete;
{
    self.countIdx++;
    DebugNSLog(@"recv history 1 idx: %ld, all:%ld", self.countIdx, self.allCount);
    if (hisData) {
        [self.hisCacheArray addObject:hisData];
        NSString *log = [NSString stringWithFormat:@"%ld %@", self.countIdx, [hisData wholeDesc]];
        [self.textView addNewText:log];
//        [self.textView addNewText:[NSString stringWithFormat:@"recv history 1 idx: %ld, all:%ld", self.countIdx, self.allCount]];
    }
    if (isComplete) {
        [self.textView addNewText:@"Sync complete, ready calculate sleep..."];
        [self calcSleep];

    }
    
    
}

- (void)caBleHistoryDataCount:(NSInteger)count { 
    [self.textView addNewText:[NSString stringWithFormat:@"history 1 count: %ld", (long)count]];
    self.countIdx = 0;
    self.allCount = count;
}

- (void)srBleHistoryDataTimeout { 
    [self.textView addNewText:@"Sync history 1 time out!"];
}


- (void)caBleIsBinded:(BOOL)isBinded { 
    
}

- (void)caBleMeasureDuration:(NSInteger)seconds { 
    
}

- (void)caBleOEMAuthResult:(BOOL)authSucceddful { 
    
}

- (void)caBleRealtimeHRV:(nonnull NSNumber *)hrv BloodOxygen:(nonnull NSNumber *)bloodOxygen HeartRate:(nonnull NSNumber *)hr Status:(REALTIME_STATUS)status { 
    
}

- (void)caBleSN:(nonnull NSString *)sn SnData:(nonnull NSData *)snData { 
    
}


@end
